
import reduxthunk from 'redux-thunk';
// 01:
import { legacy_createStore as createStore, applyMiddleware, compose } from 'redux'
// 02:
const defaultstate = {
    schoolArr: []
}
// 03: 
const reducer = (state = defaultstate, actions) => {
    if (actions.type == 'setschool') {
        return {
            schoolArr: actions.payload
        }
    }
    if (actions.type == 'add') {
        let obj = {
            id: state.schoolArr[state.schoolArr.length - 1].id * 1 + 1,
            school_name: actions.payload
        }
        state.schoolArr.push(obj);
        // 这样返回的新的state 替换掉了原state数据, 实现数据的更新, 注意这里是替换不是合并 
        return {
            schoolArr: state.schoolArr
        }
    }
    if (actions.type == 'del') {
        // console.log(actions.payload);
        let newArr = state.schoolArr.filter((item) => {
            return item.id != actions.payload
        })
        // 这样返回的新的state 替换掉了原state数据, 实现数据的更新, 注意这里是替换不是合并 
        return {
            schoolArr: newArr
        }
    }

    //定义编辑
    if (actions.type == 'edit') {
        let newArr = state.schoolArr.map((item) => {
            if (item.id == actions.payload.id) {
                item.school_name = actions.payload.school_name
            }
            return item
        })
        return {
            schoolArr: newArr
        }

    }

    return state
}

// 04: 
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, /* preloadedState, */ composeEnhancers(
    applyMiddleware(reduxthunk)
));

// 05:
export default store